# -*- coding: utf-8 -*-
from jinja2 import PackageLoader
from odoo import http
from odoo.http import request
import jinja2
import logging
import json
import datetime

_logger = logging.getLogger(__name__)
env = jinja2.Environment(
    loader=PackageLoader('odoo.addons.er', 'views/jinja'), autoescape=True)
env.filters["json"] = json.dumps


class ERMap(http.Controller):

    # 救援客户端地图

    @http.route("/er/client/map/get/all/cars", auth="public", type="http")
    def get_all_cars(self, **kw):
        """
        获取所有车辆信息
        :param kw:
        :return:
        """
        cars = request.env["tyibs.base.maintenance.rescue.vehicle"].sudo().search([])
        return json.dumps([{'car_id': car.id, 'device_code': car.GPS_code, 'code': car.code, 'manager': car.manager} for car in cars])

    @http.route("/er/client/map/get/all/save/company", auth="public", type="http", csrf=False)
    def get_all_save_company(self, **kw):
        """
        获取所有救援单位，包含电梯本身的维保单位
        :param kw:
        :return:
        """
        domain = [('is_salvager_unit','=',True)]
        if kw.get("maintenance_id", False):
            domain = ['|',('is_salvager_unit','=',True),('id', '=', kw.get("maintenance_id"))]
        company_ids = request.env["tyibs.base.maintenance.company"].sudo().search(domain)
        return json.dumps([{'id': item.id,
                            'name': item.name,
                            'address': item.address,
                            'contact': item.contact,
                            'mobile': item.mobile,
                            'phone': item.phone,
                            'lng': item.ln,
                            'lat': item.la} for item in company_ids])

    @http.route("/er/client/map/get/response/company/<int:company_id>", auth="public", type="http")
    def get_response_company(self, company_id, **kw):
        """
        获取响应单位信息
        :param company_id:
        :param kw:
        :return:
        """
        company = request.env['tyibs.base.maintenance.company'].sudo().browse(company_id)
        return json.dumps({ 'name': company.name,
                            'address': company.address,
                            'contact': company.contact,
                            'mobile': company.mobile,
                            'phone': company.phone,
                            'lng': company.ln,
                            'lat': company.la})

    @http.route("/er/client/map/dispatch/save/order/<int:order_id>", auth="public", type="http")
    def save_dispatch_map(self, order_id, **kw):
        """
        调度时的地图
        :param kw:
        :return:
        """
        order = request.env['tyibs.er.work.order.save'].sudo().browse(order_id)
        return env.get_template("client/dispatch.html").render({
            'lift': order.lift_id,
            'car_id': order.car_id.id or "",
            'order_id': order.id,
        })

    @http.route("/er/client/map/track/save/order/<int:order_id>", auth="public", type="http")
    def save_track_map(self, order_id, **kw):
        """
        救援跟踪时的地图
        :param kw:
        :return:
        """
        order = request.env['tyibs.er.work.order.save'].sudo().browse(order_id)
        return env.get_template("client/track.html").render({
            'lift': order.lift_id,
            'car_id': order.car_id.id or "",
            'device_code': order.car_id.GPS_code or "",
            'order_id': order.id,
            'response_company_id': order.response_maintenance_company_id.id or ""
        })

    @http.route("/er/client/map/dispatch/car/<string:device_code>", auth="public", type="http")
    def get_car_info_by_device_code(self, device_code, **kw):
        """
        根据设备GPS CODE获取车辆信息
        :param kw:
        :return:
        """
        car = request.env["tyibs.base.maintenance.rescue.vehicle"].sudo().search([('GPS_code', '=', device_code)])
        return json.dumps({
            'car_id': car.id,
            'device_code': device_code,
            'enterprise_id': car.enterprise_id.id or u"未知",
            'enterprise_name': car.enterprise_id.name or u"未知",
            'code': car.code or u"未知",
            'GPS_mobile': car.GPS_mobile or u"未知",
            'manager': car.manager or u"未知",
            'manager_mobile': car.manager_mobile or u"未知"
        })

    # @http.route("/er/client/map/dispatch/save/order/<int:order_id>/set/car", auth="public", csrf=False)
    # def save_order_set_car(self, order_id, **kw):
    #     """
    #     设置救援工单的救援车辆
    #     :param car_id:救援车辆的id
    #     :param kw:
    #     :return:
    #     """
    #     result = {'error_code': 0, "error_msg": "success"}
    #     try:
    #         order = request.env['tyibs.er.work.order.save'].sudo().browse(order_id)
    #         if not kw.get("car_id", False) or kw.get("car_id") == "undefined" or kw.get("car_id") == "false":
    #             result["error_code"] = 1
    #             result["error_msg"] = u"无车辆ID"
    #             return json.dumps(result)
    #         car = request.env["tyibs.base.maintenance.rescue.vehicle"].browse(int(kw.get("car_id")))
    #         if not car:
    #             result["error_code"] = 1
    #             result["error_msg"] = u"系统中没有这辆车"
    #             return json.dumps(result)
    #         order.write({
    #             'car_id': car.id,
    #             'response_type': 'maintenance',
    #             'response_maintenance_company_id': car.enterprise_id.id,
    #             'response_company_name': car.enterprise_id.name,
    #             'response_person_name': car.manager,
    #             'response_person_mobile': car.enterprise_id.name,
    #             'response_time': datetime.datetime.utcnow(),
    #         })
    #         return json.dumps(result)
    #     except Exception, e:
    #         result["error_code"] = 1
    #         result["error_msg"] = e.message
    #         return json.dumps(result)

    @http.route("/er/client/map/index", auth="public", type="http")
    def er_map_index(self, **kw):
        """
        救援客户端首页，没有选电梯
        :param kw:
        :return: 无返回值
        """
        return env.get_template("client/index_map.html").render()

    @http.route("/er/client/map/index/lift/<int:lift_id>", auth="public", type="http")
    def er_map_index_has_lift(self, lift_id, **kw):
        """
        救援客户端首页，选了电梯
        :param lift_id: 电梯ID
        :param kw:
        :return: 无返回值
        """
        lift = request.env["tyibs.base.lift"].sudo().browse(lift_id)
        render_data = {}
        if lift:
            render_data["lift_code"] = lift.code
            render_data["lift_id"] = lift.id
            render_data["lift_gps_address"] = lift.gps_address
            render_data["lift_address"] = lift.use_address
            render_data["lift_lng"] = lift.ln
            render_data["lift_lat"] = lift.la
            render_data["use_company_name"] = lift.use_company_id.name
        return env.get_template("client/index_map.html").render(render_data)
